<?php

/**
 * RoleService.class.php 
 * 
 *
 * @author     late.xiao@qq.com
 */
namespace Sysmanger\Service;

class RoleService extends BaseService {

    public function delRole($role_id)
    {
        if(!$role_id)
        {
            return false;
        }
        
        $role_mdl = D('manager_role');
        $manger_mdl = D('manager');
        try {
            $role_mdl->startTrans();
            $where['role_id'] = $role_id;
            $role_mdl->where($where)->delete();
            $data['disable'] = 1;
            $manger_mdl->where($where)->save($data);
            $role_mdl->commit();
        } catch (\Exception $e) {
            $role_mdl->rollback();
            return false;
        }
        
        return true;
    }
    
    public function getRoleList($params)
    {
        if(!$params)
        {
            return false;
        }
        
        $mdl = D('manager_role');
        
        $count = $mdl->count();
        if(!$count)
        {
            return false;
        }
        
        $list = $mdl->field($params['fields'])->order($params['order'])->limit($params['start'], $params['limit'])->select();
        
        return array(
                'count'=>$count,
                'list'=>$list
        );
    }
    
    public function saveRole($data)
    {
        $errors = array();
        $options = array(
                'role_name' =>array(
                        'required' => array(
                                'rule'=>true,
                                'message'=>'角色名必填'
                        ),
                        'string_count_in_range' => array(
                                'rule'=>array(2,15),
                                'message'=>'角色名在2至15个长度之间'
                        ),
                ),
                'permission' =>array(
                        'required' => array(
                                'rule'=>true,
                                'message'=>'请设置权限'
                        ),
                ),
        );
        $rs = \Base\Lib\Tools\Validator::make($errors, $data, $options);
        if(!$rs)
        {
            foreach ($errors as $k=>$v)
            {
                throw new \Exception($v);
            }
        }
        
        $obj_role_mdl = D('manager_role');
        if($data['role_id'])
        {
            $data['updated'] = NOW_TIME;
            $where['role_id'] = $data['role_id'];
            unset($data['role_id']);
            return $obj_role_mdl->where($where)->save($data);
        }
        
        $data['created'] = $data['updated'] = NOW_TIME;
        
        return $obj_role_mdl->data($data)->add();
    }
}
 